<?php

class Bridge_Cache
{
	private $expiry;
	
	public function __construct($config)
	{
		$connection = (string) $config->cache->connection;
		$username = (string) $config->cache->username;
		$password = (string) $config->cache->password;
		
		$expiry = (string) $config->cache->expiry;
	
		if ( $expiry != "" )
		{
			$this->expiry = time() - ( $expiry * 60 );
		}
		else
		{
			$this->expiry = 0;
		}

		$this->objPDO = new PDO($connection, $username, $password);
		$this->objPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	}

	public function get($id, $type)
	{
		$strSQL = "SELECT * FROM bridge_cache where id = :id and type = :type and timestamp > :expiry";
		
		$objStatement = $this->objPDO->prepare($strSQL);
		$objStatement->bindValue( ":id", $id);
		$objStatement->bindValue( ":type", $type);
		$objStatement->bindValue( ":expiry", $this->expiry);
		$objStatement->execute();
				
		$results = $objStatement->fetchAll();		
		
		if ( count($results) == 0 )
		{
			return null;
		}
		else
		{
			$objXml = new DOMDocument();
			$objXml->loadXML( $results[0]["data"] );
			
			return $objXml;
		}
	}
	
	public function set($id, $type, $data)
	{
		if ( ! $data instanceof DOMDocument )
		{
			throw new Exception("data must be of type DOMDocumenbt");
		}
		
		$strSQL = "REPLACE INTO bridge_cache (id, type, timestamp, data) VALUES(:id, :type, :timestamp, :data)";
		
		$objStatement = $this->objPDO->prepare($strSQL);
		$objStatement->bindValue( ":id", $id);
		$objStatement->bindValue( ":type", $type);
		$objStatement->bindValue( ":timestamp", time());
		$objStatement->bindValue( ":data", $data->saveXML());
				
		return $objStatement->execute();	
	}
}
